<template>
  <uni-nav-bar title="提现" color="#333" left-icon="left" @clickLeft="navBack" statusBar></uni-nav-bar>
  <environment></environment>
  <view class="flex-col-hcenter">
    <view class="container">
      <!-- top box -->
      <view class="top-box">
        <view class="flex" style="font-size: 26rpx; letter-spacing: 2rpx">
          <view>账户余额 {{ balance }}</view>
        </view>
        <view class="flex" style="font-size: 26rpx; letter-spacing: 2rpx; margin-top: 5rpx">
          <view>已提交提现申请金额 {{ appliedAmount }}</view>
        </view>
        <view class="flex-jcsb" style="width: 100%">
          <view>
            <view style="font-size: 30rpx; letter-spacing: 2rpx; margin-top: 20rpx">可提现金额(元)</view>
            <view class="available-amount">{{ availableAmount }}</view>
          </view>
          <view class="flex-center record-btn" @click="navTo('account/record')">提现记录</view>
        </view>
      </view>
      <!-- withdraw box -->
      <view class="withdraw-box">
        <view style="font-size: 32rpx">提现金额</view>
        <view class="amount-input-box">
          <view class="input-grid" style="border-bottom: 2rpx solid #f2f2f2" @click="openKeyPad">
            <text style="font-size: 26rpx; padding-bottom: 10rpx">¥</text>
            <text v-show="amount === ''" style="color: rgb(153, 153, 153); line-height: 30px">请输入提现金额</text>
            <text v-show="amount !== ''" style="font-size: 38rpx; line-height: 30px">{{ amount }}</text>
          </view>
          <view @click="setAllAmount" style="font-size: 30rpx">全部提现</view>
        </view>
        <!-- tip -->
        <view style="font-size: 27rpx; margin-bottom: 20rpx; min-height: 32rpx">
          <text v-show="amount !== ''" style="color: #999">
            实际到账 {{ realAmount }} 元(微信支付平台收取手续费 {{ serviceCharge }} 元)
          </text>
        </view>
        <!-- withdraw account -->
        <view class="flex-jcsb" style="margin-top: 20rpx">
          <view style="font-size: 30rpx">提现至</view>
          <view class="flex-vcenter" @click="toOpenBankPad" style="font-size: 30rpx">
            <text v-if="hasBank" style="color: #999">{{ bankInfo }}</text>
            <text v-else style="color: #333">请添加银行卡</text>
            <uni-icons type="right" color="#666" size="14"></uni-icons>
          </view>
        </view>
      </view>
      <!-- withdraw btn -->
      <view class="flex-center withdraw-confirm-btn" :class="isDisabled ? 'disabled' : ''" @click="toWithdraw">
        确定提现
      </view>
      <!-- tip box -->
      <view class="tip-box"><view style="margin-top: 20rpx" v-html="tipContent"></view></view>
    </view>
    <!-- IntKeyPad popup -->
    <uni-popup ref="IntKeyPadPopup" type="bottom" :is-mask-click="false">
      <view class="flex-hcenter" style="background: #eff4f8">
        <IntKeyPad @key-click="keyClick" @confirm="closeKeyPad" />
      </view>
    </uni-popup>
    <!-- confirm popup -->
    <Confirm ref="confirmPopup" title="提 现" @cancel="closeConfirm" @confirm="withdraw" />
    <!-- binding popup -->
    <uni-popup ref="BankPadPopup" type="bottom" :is-mask-click="false">
      <BankPad v-if="isShowBankPad" :type="bankPadType" @close="closeBankPad" />
    </uni-popup>
    <!-- 绑定手机号码弹框 -->
    <uni-popup ref="PhonePadPopup" type="bottom" :is-mask-click="false"><PhonePad @close="closePhonePad" /></uni-popup>
  </view>
</template>

<script setup lang="ts">
import environment from '@c/pobulic/environment.vue';
import { withdrawInfo } from '@/gql/account';
import { WithdrawInfoQuery } from '@/gql/types/gql';
import { getDriverID } from '@/stores/driverID';
import { useFinanceStore } from '@/stores/finance';
import { useUserStore } from '@/stores/user';
import { navBack, navTo } from '@/utils/navigator';
import { errorToast, showLoading, showToast } from '@/utils/prompt';
import BankPad from '@c/common/BankPad.vue';
import Confirm from '@c/common/Confirm.vue';
import IntKeyPad from '@c/common/IntKeyPad.vue';
import PhonePad from '@c/common/PhonePad.vue';
import { toPublish } from '@mqtt';
import { computed, ref } from 'vue';

// static
const driver_id = getDriverID();
const userInfo = useUserStore();
const financeStore = useFinanceStore();
const hasBank = computed(() => financeStore.bankID !== '');
const unappliedAmount = ref(0);
const appliedAmount = ref(0);
const balance = computed(() => (unappliedAmount.value * 100 + appliedAmount.value * 100) / 100);
const availableAmount = computed(() => Math.floor(unappliedAmount.value));
const rate = ref(0.005);
const tipContent = ref('');
const bankInfo = computed(() => (hasBank.value ? `${financeStore.bank_name}(${financeStore.card_no.slice(-4)})` : ''));

// data
const amount = ref('');
const hasAmount = computed(() => amount.value !== '');
const serviceCharge = computed(() => {
  if (hasAmount.value) {
    const fee = Number.parseFloat(amount.value) * rate.value;
    return fee < 0.1 ? '0.10' : fee.toFixed(2);
  } else {
    return '';
  }
});
const realAmount = computed(() => {
  return hasAmount.value ? (Number.parseFloat(amount.value) - Number.parseFloat(serviceCharge.value)).toFixed(2) : '';
});
const isDisabled = computed(() => !hasAmount.value || !hasBank.value);

const isShowBankPad = ref(false);
const bankPadType = ref('');

// refs
const IntKeyPadPopup = ref(null);
const confirmPopup = ref(null);
const BankPadPopup = ref(null);
const PhonePadPopup = ref(null);

function init() {
  userInfo.getUserInfo();
  showLoading();
  if (!hasBank.value) {
    financeStore.getBankInfo();
  }
  const payload = {
    query: withdrawInfo,
    variables: {
      driver_id,
      code: 'txsm',
    },
  };
  toPublish('ql/driver/withdrawInfo', payload, (obj: { data: WithdrawInfoQuery }) => {
    const { data } = obj;
    unappliedAmount.value = data.total_list.money;
    appliedAmount.value = data.total_list.total_withdraw_apply;
    rate.value = data.tx_sxf;
    tipContent.value = data.get_myblock.content;
  });
}
init();

// set amount
function openKeyPad() {
  if (availableAmount.value === 0) {
    errorToast('暂无可提现金额');
  } else {
    IntKeyPadPopup.value.open();
  }
}
function closeKeyPad() {
  IntKeyPadPopup.value.close();
}
function keyClick(key) {
  const amountValue = amount.value;
  const isEmpty = amountValue === '';
  const isBackspace = key === 'backspace';
  const isZero = key === '0';
  const isNotBigger = Number.parseFloat(amountValue + key) <= availableAmount.value;
  if (isEmpty && (isBackspace || isZero)) {
    return;
  } else if (isBackspace) {
    amount.value = amountValue.slice(0, -1);
  } else if (isNotBigger) {
    amount.value += key;
  } else {
    showToast('请勿超过可提现金额');
  }
}
function setAllAmount() {
  const amountVal = availableAmount.value;
  if (amountVal === 0) {
    errorToast('暂无可提现金额');
  } else {
    amount.value = amountVal.toString();
  }
}

// bank
function toOpenBankPad() {
  bankPadType.value = hasBank.value ? 'change' : 'bind';
  openBankPad();
}
function openBankPad() {
  isShowBankPad.value = true;
  BankPadPopup.value.open();
}
function closeBankPad() {
  isShowBankPad.value = false;
  BankPadPopup.value.close();
}

// withdraw
function toWithdraw() {
  if (!hasAmount.value) {
    showToast('请输入提现金额');
  } else if (!hasBank.value) {
    showToast('请绑定银行卡');
  } else if (!userInfo.mobile) {
    showToast('请先绑定您的手机号码');
    openPhonePad();
  } else {
    openConfirm();
  }
}
function openPhonePad() {
  PhonePadPopup.value.open();
}
function closePhonePad() {
  PhonePadPopup.value.close();
}
function openConfirm() {
  confirmPopup.value.open();
}
function closeConfirm() {
  confirmPopup.value.close();
}
function withdraw() {
  closeConfirm();
  showLoading('正在提交');
  const payload = {
    driver_id,
    method: 'mp',
    amount: Number.parseInt(amount.value),
    order_type: 'withdraw',
    bank: JSON.stringify(financeStore.bankInfo),
  };
  toPublish(
    'order_withdraw/addOrder',
    payload,
    (obj: { code: number; msg: string }) => {
      const { code, msg } = obj;
      if (code === 1) {
        userInfo.getUserInfo();
        uni.redirectTo({
          url: '/pages/account/success',
        });
      } else {
        errorToast(msg);
      }
    },
    () => errorToast('提现申请超时'),
  );
}
</script>

<style scoped lang="less">
.container {
  width: 96%;
}

.top-box {
  margin-top: 15rpx;
   background-image: url(https://admin.anlan.tech/uploads/20221023/aa78cfcec92006930c355b1305a5dbaf.png);
  background-repeat: no-repeat;
  background-size: 100%;
  height: 264rpx;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  color: white;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-between;

  .available-amount {
    font-size: 48rpx;
    letter-spacing: 4rpx;
    margin-top: 10rpx;
  }

  .available-amount::before {
    content: '¥';
    font-size: 24rpx;
    color: white;
    margin-right: 6rpx;
  }

  .record-btn {
    margin-top: 42rpx;
    margin-right: 30rpx;
    font-size: 26rpx;
    letter-spacing: 4rpx;
    width: 170rpx;
    height: 48rpx;
    border-radius: 5px;
    border: 2rpx solid #f2f2f2;
  }
}

.withdraw-box {
  margin-top: 15rpx;
  background: white;
  box-shadow: 2rpx 4rpx 8rpx 0 rgba(204, 204, 204, 0.5);
  border-radius: 5px;
  padding: 30rpx 24rpx 22rpx;
  font-size: 28rpx;
  letter-spacing: 4rpx;
  color: #333;

  .amount-input-box {
    margin: 25rpx 0 10rpx;
    display: grid;
    grid-template-columns: 500rpx 150rpx;
    column-gap: 40rpx;
    grid-template-rows: 54rpx;
    align-items: flex-end;

    .input-grid {
      display: grid;
      grid-template-columns: 30rpx 420rpx;
      align-items: flex-end;
    }
  }
}

.withdraw-confirm-btn {
  width: 260rpx;
  height: 80rpx;
  background: linear-gradient(69deg, #41a3ff 0%, #1b91ff 100%);
  border-radius: 5px;
  margin: 130rpx auto 0;
  font-size: 36rpx;
  letter-spacing: 6rpx;
  color: white;

  &.disabled {
    background: #999;
  }
}

.tip-box {
  width: 100%;
  margin: 114rpx 0 40rpx;
  padding-left: 34rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  letter-spacing: 2rpx;
  color: #666;
}

.popup-content {
  width: 750rpx;
}

.btn-box {
  font-size: 36rpx;
  letter-spacing: 12rpx;
  padding: 60rpx 80rpx;

  .btn {
    width: 260rpx;
    height: 80rpx;
  }

  .btn-cancel {
    color: #1b91ff;
    border-radius: 5px;
    border: 2rpx solid #1b91ff;
  }

  .btn-confirm {
    color: white;
    background: linear-gradient(69deg, #41a3ff 0%, #1b91ff 100%);
    border-radius: 5px;
  }
}

.withdraw-popup {
  background-color: #fff;
  border-radius: 5px;

  .title-box {
    height: 100rpx;
    border-bottom: 2rpx solid #f2f2f2;
    font-size: 34rpx;
    color: #333;
    word-spacing: 12rpx;
  }

  .btn-grid {
    display: grid;
    grid-template-columns: repeat(2, 228rpx);
    column-gap: 108rpx;
    padding: 38rpx 58rpx;
  }
}
</style>
